package com.bkgy.controller.tcmReport.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.commom.model.Temp;
import com.bkgy.commom.model.Temp2;
import com.bkgy.controller.repOutput.entity.RepOutput;
import com.bkgy.controller.repOutput.service.IRepOutputService;
import com.bkgy.controller.tcmReport.entity.RepTcmOutputPlanAct;
import com.bkgy.controller.tcmReport.entity.pdo.FeiciRep;
import com.bkgy.controller.tcmReport.entity.pdo.PlanActRes;
import com.bkgy.controller.tcmReport.mapper.IRepTcmOutputPlanActMapper;
import com.bkgy.controller.tcmReport.service.IRepTcmOutputPlanActService;
import com.bkgy.controller.technology.entity.TDefectData;
import com.bkgy.controller.technology.service.ITDefectDataService;
import com.bkgy.controller.tpdol3data.entity.OutputSec;
import com.bkgy.modular.tpdidata_cal1630.service.ITPdiDataMesService;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class RepTcmOutputPlanActServiceImpl extends ServiceImpl<IRepTcmOutputPlanActMapper, RepTcmOutputPlanAct> implements IRepTcmOutputPlanActService {
    private final IRepTcmOutputPlanActMapper mapper;
    private final ITPdiDataMesService pdiMesService;
    private final IRepOutputService repOutputService;
    private final ITDefectDataService defectService;

    @Override
    public ResultData<PlanActRes> findOutputPlanAct() {
        LambdaQueryWrapper<RepTcmOutputPlanAct> w = new LambdaQueryWrapper<>();
        String d = DateUtil.getDateToString(new Date(), "yyyyMMdd");
        w.eq(RepTcmOutputPlanAct::getShijian, d).eq(RepTcmOutputPlanAct::getLineCode, "tcm2280");
        RepTcmOutputPlanAct rep = getOne(w);

        PlanActRes res = new PlanActRes();
        if (rep != null) {
            res.setDayPlan(rep.getDayPlan());
            res.setDayPlanXiada(rep.getDayPlanXiada());
            LambdaQueryWrapper<RepOutput> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RepOutput::getLineName, "tcm2280");
            RepOutput repOutput = repOutputService.getOne(wrapper);
            BigDecimal outMatWt = repOutput.getRichan();
            res.setDayAct(outMatWt);
            BigDecimal planRate = BigDecimal.ZERO;
            BigDecimal actRate = BigDecimal.ZERO;
            if (rep.getDayPlan().compareTo(BigDecimal.ZERO) > 0) {
                planRate = rep.getDayPlanXiada().multiply(BigDecimal.valueOf(100)).divide(rep.getDayPlan(), 2, RoundingMode.HALF_UP);
                actRate = outMatWt.multiply(BigDecimal.valueOf(100)).divide(rep.getDayPlan(), 2, RoundingMode.HALF_UP);
            }
            res.setDayPlanRate(planRate);
            res.setDayActRate(actRate);
        }

        return ResultData.ResultDataSuccess(res);
    }

    @Override
    public void initDayPlanXiadaJob(Date d1) {
        //月计划量
        String month = DateUtil.getDateToString(d1, "yyyyMM");
        String day = DateUtil.getDateToString(d1, "dd");
        BigDecimal plan = mapper.selectPlan(month);
        //月停机总时长
        BigDecimal monthDuration = BigDecimal.ZERO;
        long dayDuration = 0;
        List<Temp2> durationList = mapper.selectDuration(month);
        for (Temp2 temp2 : durationList) {
            if (day.equals(temp2.getK())) {
                dayDuration = temp2.getV();
            }
            monthDuration = monthDuration.add(BigDecimal.valueOf(temp2.getV()));
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(d1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        //一个月的分钟数
        int monthMinis = cal.getActualMaximum(Calendar.DAY_OF_MONTH) * 24 * 60;
        //日计划产量 = DAY_OUTPUT/（总分钟数-检修分钟）*60*24
        BigDecimal dayPlan = plan.multiply(BigDecimal.valueOf(24 * 60)).divide(BigDecimal.valueOf(monthMinis).subtract(monthDuration), 2, RoundingMode.HALF_UP);

        //日计划下达产量=一天时间-计划停机时间，用秒用时累计
        OutputSec sec = pdiMesService.sumOutputSecInfo(cal.getTime(), (24 * 60 - dayDuration) * 60);
        BigDecimal dayXiaoda = sec.getTotalOutput();

        RepTcmOutputPlanAct rep = new RepTcmOutputPlanAct();
        rep.setShijian(DateUtil.getDateToString(d1, "yyyyMMdd"));
        rep.setLineCode("tcm2280");
        rep.setDayPlan(dayPlan);
        rep.setDayPlanXiada(dayXiaoda);
        saveOrUpdate(rep);
    }

    @Override
    public void updateLastDayOutputJob(Date yestoday) {
        String beginDate = DateUtil.getDateToString(DateUtil.getCurrentZero(yestoday), "yyyyMMdd");
        String endDate = DateUtil.getDateToString(DateUtil.getNextDayZero(yestoday), "yyyyMMdd");
        //查询全部缺陷记录，并去重
        LambdaQueryWrapper<TDefectData> w1 = new LambdaQueryWrapper<>();
        w1.ge(TDefectData::getDefectVersionTime1, beginDate);
        w1.lt(TDefectData::getDefectVersionTime1, endDate);
        w1.orderByAsc(TDefectData::getDefectVersionTime1);
        List<TDefectData> defectList = defectService.list(w1);
        Map<String, TDefectData> defectMap = new HashMap<>();
        for (TDefectData defect : defectList) {
            defectMap.put(defect.getExtId(), defect);
        }

        Map<String, List<FeiciRep>> lineDefectMap = new HashMap<>();
        //寻找各个缺陷的归户
        //L611酸轧、L612连退2150、L613连退1630、L614重卷1组、L615重卷2组、L616重卷3组、L621镀锌5#、L622镀锌6#
        BigDecimal[] feicijiangArr = new BigDecimal[]{BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO};
        List<String> notExitList = new ArrayList<>();
        int[] countArr = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
        Collection<TDefectData> defects = defectMap.values();
        for (TDefectData defect : defects) {
            FeiciRep feici = new FeiciRep();
            String extid = defect.getExtId();
            String unitCode = defect.getUnitCode();
            int zuizhongCode = getSufaceCode(defect.getDefectClass1());

            feici.setUnitCode(defect.getUnitCode());
            feici.setDefectClass1(defect.getDefectClass1());
            feici.setDefectComment1(defect.getDefectComment1());

            //依次从酸轧、2150、镀锌、1630产线搜寻
            Temp temp = null;
            temp = mapper.selectSurfaceByTcm(extid);
            if (temp == null) {
                temp = mapper.selectSurfaceByCal2150(extid);
                if (temp == null) {
                    temp = mapper.selectSurfaceByCgl(extid);
                    if (temp == null) {
                        temp = mapper.selectSurfaceByCal1630(extid);
                        if (temp != null) {
                            feici.setTcmExtid(temp.getK2());
                            feici.setYaoqiuCode(temp.getK1());
                            feici.setCal1630Extid(extid);
                            feici.setOutMatWt(temp.getV());
                            countArr[6]++;
                        }
                    } else {
                        feici.setYaoqiuCode(temp.getK1());
                        feici.setCglExtid(extid);
                        feici.setOutMatWt(temp.getV());
                        countArr[5]++;
                    }
                } else {
                    feici.setTcmExtid(temp.getK2());
                    feici.setYaoqiuCode(temp.getK1());
                    feici.setCal2150Extid(extid);
                    feici.setOutMatWt(temp.getV());
                    countArr[4]++;
                }
            } else {
                feici.setYaoqiuCode(temp.getK1());
                feici.setTcmExtid(extid);
                feici.setOutMatWt(temp.getV());
                countArr[3]++;
            }

            //到重卷产线搜寻
            if (temp == null) {
                temp = mapper.selectRc1(extid);
                if (temp == null) {
                    temp = mapper.selectRc2(extid);
                    if (temp == null) {
                        temp = mapper.selectRc3(extid);
                        if (temp != null) {
                            feici.setRcl3Extid(extid);
                            countArr[2]++;
                        }
                    } else {
                        feici.setRcl2Extid(extid);
                        countArr[1]++;
                    }
                } else {
                    feici.setRcl1Extid(extid);
                    countArr[0]++;
                }

                //进一步根据重卷的入口卷号查找来源产线，进而获取原始表面等级
                if (temp != null) {
                    String entid = temp.getK();
                    BigDecimal outMatWt = temp.getV();//使用重卷中的出口重量
                    feici.setOutMatWt(outMatWt);
                    //进一步查找表面等级
                    temp = mapper.selectSurfaceByTcm(entid);
                    if (temp == null) {
                        temp = mapper.selectSurfaceByCal2150(entid);
                        if (temp == null) {
                            temp = mapper.selectSurfaceByCgl(entid);
                            if (temp == null) {
                                temp = mapper.selectSurfaceByCal1630(entid);
                                if (temp != null) {
                                    feici.setCal1630Extid(entid);
                                    feici.setTcmExtid(temp.getK2());
                                }
                            } else {
                                feici.setCglExtid(entid);
                            }
                        } else {
                            feici.setTcmExtid(temp.getK2());
                            feici.setCal2150Extid(entid);
                        }
                    } else {
                        feici.setYaoqiuCode(temp.getK1());
                        feici.setTcmExtid(temp.getK2());
                    }
                    if (temp != null) {
                        temp.setV(outMatWt);
                    } else {
                        feici.setUnknowExtid(extid);
                    }
                }
            }

            if (temp != null) {
                int yaoqiuCode = getSufaceCode(temp.getK1());
                BigDecimal outMatWt = temp.getV();
                if (yaoqiuCode > zuizhongCode) {
                    dealFeicijiang(feicijiangArr, unitCode, outMatWt);

                    if (!lineDefectMap.containsKey(unitCode)) {
                        List<FeiciRep> feiciList = new ArrayList<>();
                        feiciList.add(feici);
                        lineDefectMap.put(unitCode, feiciList);
                    } else {
                        lineDefectMap.get(unitCode).add(feici);
                    }
                }
            } else {
                log.warn("计算废次降查找不到卷号：{}归属产线", extid);
                notExitList.add(extid);
            }
        }

        LambdaQueryWrapper<RepTcmOutputPlanAct> w = new LambdaQueryWrapper<>();
        w.eq(RepTcmOutputPlanAct::getShijian, DateUtil.getDateToString(yestoday, "yyyyMMdd"));
        w.eq(RepTcmOutputPlanAct::getLineCode, "tcm2280");
        RepTcmOutputPlanAct rep = new RepTcmOutputPlanAct();
        rep.setFeiCiJiang(feicijiangArr[0]);
        rep.setDayAct(mapper.selectDayOutput(beginDate, endDate));
        update(rep, w);

//        List<FeiciRep> tcm2280 = lineDefectMap.get("L611");
//        for (FeiciRep feici : tcm2280) {
//            System.out.println(feici.getUnitCode() + "\t" + feici.getTcmExtid() + "\t" + feici.getCal2150Extid() + "\t" + feici.getCal1630Extid() + "\t" +
//                    feici.getCglExtid() + "\t" + feici.getRcl1Extid() + "\t" + feici.getRcl2Extid() + "\t" + feici.getRcl3Extid() + "\t" + feici.getOutMatWt());
//        }
    }

    private void dealFeicijiang(BigDecimal[] arr, String unitCode, BigDecimal feicijiang) {
        //L611酸轧、L612连退2150、L613连退1630、L614重卷1组、L615重卷2组、L616重卷3组、L621镀锌5#、L622镀锌6#
        if ("L611".equals(unitCode)) {
            arr[0] = arr[0].add(feicijiang);
        } else if ("L612".equals(unitCode)) {
            arr[1] = arr[1].add(feicijiang);
        } else if ("L613".equals(unitCode)) {
            arr[2] = arr[2].add(feicijiang);
        } else if ("L614".equals(unitCode)) {
            arr[3] = arr[3].add(feicijiang);
        } else if ("L615".equals(unitCode)) {
            arr[4] = arr[4].add(feicijiang);
        } else if ("L616".equals(unitCode)) {
            arr[5] = arr[5].add(feicijiang);
        } else if ("L621".equals(unitCode)) {
            arr[6] = arr[6].add(feicijiang);
        } else if ("L622".equals(unitCode)) {
            arr[7] = arr[7].add(feicijiang);
        }
    }

    private int getSufaceCode(String defectClass) {
        //0认为正常
        if ("0".equals(defectClass)) {
            return 100;
        }

        int result = 0;
        if (StringUtils.isNumeric(defectClass)) {
            result = Integer.parseInt(defectClass);
        }
        return result;
    }
}
